python替换操作(replace,re.sub) 您所在的位置:网站首页 chiara provasi怎么读 python替换操作(replace,re.sub)

python替换操作(replace,re.sub)

2024-03-04 11:25| 来源: 网络整理| 查看: 265

python替换的几种操作:

主要replace(),re.sub(),以及split()切片替换

一:简单的某个字符替换:

replace()函数

str.replace(old, new, num)

Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换 num 次。 eg:

str = 'hello world!! ' print(str.replace('!',',',1)) print(str.replace('!',','))

结果: 在这里插入图片描述

二:使用切片split()和join实现

这个在上篇 第六点里面也写过

str = 'hello world!! ' new = '_hi' new_str = str.split('!') print(new.join(new_str))

在这里插入图片描述

三:正则替换

re.sub(pattern,repl,string,conut=0,flags=0)

参数:pattern正则表达式,repl要替换内容,string包含被替换内容的字符串,count查找替换的次数,返回一个string

如果没有找到匹配的,返回原字符串

import re str = 'hello world!! ' print(re.sub(r'[!]','_',str))

结果 在这里插入图片描述 例如Windows系统上创建的txt文档名字不能包含特殊的字符 \ / : * ? " < > | 我们可以

def setFileTitle(self,filename): fileName = re.sub(r'[\/:*?"|]','-',filename)#去掉非法字符 self.file = open(fileName + ".txt","w+")


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有